package com.itic.mall.mobile.gzh;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.type.PayType;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.orders.detail.persistence.model.OrdersDetail;
import com.itic.mall.system.orders.detail.service.OrdersDetailService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.users.userstoken.persistence.model.UsersToken;

/**
 * 京东接口
 * 
 * @author 王文鑫
 * @date 2017年12月22日 上午10:33:24
 */
@Controller
@RequestMapping(value = "/mobile/gzh")
public class GzhInterface extends BaseMobileInterface {

	@Autowired
	private OrdersDetailService ordersDetailService;
	
	   /**
	    *根据手机号码判断是否
	    * @return 
	    */
	   @RequestMapping(value="/verifyPhone")
	   @ResponseBody
	   public Map<String,Object> verifyPhone( HttpServletRequest request,HttpServletResponse response, String phone ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		if( StringHelper.isNotBlank(phone) ){
		   			UsersMall user = getUsersByPhone(phone);
		   			if( null != user && StringHelper.isNotBlank(user.getOpenid()) ){
		   				resultMap.put(DATA, "regedAndBinded");//老用户且已绑定微信公众号
		   			}
		   			
		   			if( null != user && StringHelper.isBlank(user.getOpenid()) ){
		   				resultMap.put(DATA, "regedButNoBinded");//老用户且未绑定微信公众号
		   			}
		   			
		   			if( null == user ){
		   				resultMap.put(DATA, "noReged");//全新的用户
		   			}
		   			errorCode = SUCCESS_ERROR_CODE;
			       	errorMsg = SUCCESS_ERROR_MSG;
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("GzhInterface", "author", e.toString(),"授权用户是否注册",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }  
	
	   /**
	    *微信授权登入
	    * @return 
	    */
	   @RequestMapping(value="/author")
	   @ResponseBody
	   public Map<String,Object> author( HttpServletRequest request,HttpServletResponse response, String openid ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		if( StringHelper.isNotBlank(openid) ){
		   			UsersMall user = getUsersByOpenid(openid);
		   			if( null != user ){
		   				Map<String, Object> dataMap = new HashMap<String,Object>();
		   				
		   				UsersToken usersToken = createToken(user, "gzh");
		   		     	//同步数据库
	   					usersTokenService.add(usersToken);
	   					
		   				dataMap.put("token", usersToken.getAccessToken());
		   				dataMap.put("expiredTime", usersToken.getExpiredTime());
		   				dataMap.put("userid", user.getId());
		   				resultMap.put(DATA, dataMap);
		   				
		   				errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
		   			}else{
		   				errorCode = LOGIN_ERROR_CODE;
				       	errorMsg = LOGIN_ERROR_MSG;
		   			}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("GzhInterface", "author", e.toString(),"授权用户是否注册",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }  
	   
	   /**
	    *微信公众号注册新用户返回token信息
	    * @return 
	    */
	   @RequestMapping(value="/bind")
	   @ResponseBody
	   public Map<String,Object> bind( HttpServletRequest request,HttpServletResponse response, String code , UsersMall user ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		if( StringHelper.isNotBlank(user.getUserPhone()) && StringHelper.isNotBlank(user.getOpenid()) && StringHelper.isNotBlank(code) ){
		   		    //判断手机号码是否注册过
		   			UsersMall usersTemp = usersMallService.getByPhone(user.getUserPhone());
		   			if( null != usersTemp ){
		   				if( StringHelper.isNotBlank( usersTemp.getOpenid()) ){
		   				    //提示该用户已绑定了微信公众号，无法绑定
			   				errorCode = USER_BINDED_ERROR_CODE;
					       	errorMsg = USER_BINDED_ERROR_MSG;
		   				}else{
		   				    usersTemp.setOpenid(user.getOpenid());
		   				    usersTemp.setUnionid(user.getUnionid());
		   				    //更新用户昵称
		   				    if( StringHelper.isBlank(usersTemp.getUserNickName()) && StringHelper.isNotBlank(user.getUserNickName()) ){
		   				    	usersTemp.setUserNickName(user.getUserNickName());
		   				    }
		   				    //更新用户头像
		   				    if( StringHelper.isBlank(usersTemp.getUserHeadImg()) && StringHelper.isNotBlank(user.getUserHeadImg()) ){
		   				    	usersTemp.setUserHeadImg(user.getUserHeadImg());
		   				    }
		   				    usersMallService.edit(usersTemp);
			   				errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
		   				}
		   			}else{
		   		     	//提示未找到用户，无法绑定
		   				errorCode = USER_NULL_ERROR_CODE;
				       	errorMsg = USER_NULL_ERROR_MSG;
		   			}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("GzhInterface", "register", e.toString(),"公众号注册",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }  
	   
	   
	   /**
	    *微信公众号注册新用户返回token信息
	    * @return 
	    */
	   @RequestMapping(value="/reg")
	   @ResponseBody
	   public Map<String,Object> reg( HttpServletRequest request,HttpServletResponse response, String code, UsersMall user ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		if( StringHelper.isNotBlank(code) && StringHelper.isNotBlank(user.getUserPhone()) ){
		   		    //判断手机号码是否注册过
		   		    //验证码是否有效code
	   				if( isEffectiveCode(user.getUserPhone(),code) ){
	   				 //判断手机号码是否注册过
			   			UsersMall usersTemp = usersMallService.getByPhone(user.getUserPhone());
	   					//判断 手机号码是否注册过平台，没有的话就注册
	   					if( null != usersTemp ){
	   						usersTemp.setOpenid(user.getOpenid());
	   						usersTemp.setUnionid(user.getUnionid());
	   						usersMallService.edit(usersTemp);
	   						
	   					}else{
	   						user.setLaiyuan("公众号");
	   						usersTemp = usersMallService.reg(user);
	   						
	   					}
	   					
			   			//创建新的TOKEN
			   			UsersToken usersToken = createToken(usersTemp, "gzh");
	   					//同步数据库
	   					usersTokenService.addAndSyncOther(usersToken);
			   			resultMap.put(DATA, usersToken.getAccessToken());
			   			errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
	   				}else{
				   		errorCode = PHONE_CODE_ERROR_CODE;
				       	errorMsg = PHONE_CODE_ERROR_MSG;
	   				}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("GzhInterface", "register", e.toString(),"公众号注册",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   } 
	   
	
	
	  /**
	    * 判断是否有微信openid
	    * @return 
	    */
	   @RequestMapping(value="/isHaveOpenid")
	   @ResponseBody
	   public Map<String,Object> isHaveOpenid( HttpServletRequest request,HttpServletResponse response, String token, String appId ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		
		   		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(appId) ){
		   			UsersMall user = getUsersByTokenAndAppId(token, appId);
		   			if( null != user ){
		   				if( StringHelper.isNotBlank(user.getOpenid()) ){
		   					resultMap.put(DATA, "have");
		   				}else{
		   					resultMap.put(DATA, "none");
		   				}
		   				errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
		   			}else{
		   				errorCode = LOGIN_ERROR_CODE;
				       	errorMsg = LOGIN_ERROR_MSG;
		   			}
		   		}
		   		
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("GzhInterface", "isHaveOpenid", e.toString(),"判断是否有微信openid",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	

	  /**
	    *测试
	    * @return 
	    */
	   @RequestMapping(value="/getOrderByOrderNum")
	   @ResponseBody
	   public Map<String,Object> getOrderByOrderNum( HttpServletRequest request,HttpServletResponse response, String orderNum ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		
		   		if( StringHelper.isNotBlank(orderNum) ){
		   			OrdersDetail ordersDetail = ordersDetailService.getOrdersDetailByOrderNo(orderNum);
		   			if( null != ordersDetail ){
		   				Map<String, Object> dataMap = new HashMap<String,Object>();
		   				dataMap.put("totalMoney", ordersDetail.getActualPay() );
		   				String userId = ordersDetail.getUserId();
		   				UsersMall user = usersMallService.get(userId);
		   				if( StringHelper.isNotBlank(user.getOpenid()) ){
		   					dataMap.put("openid", user.getOpenid());
			   				resultMap.put(DATA, dataMap);
			   				errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
		   				}else{
		   					errorCode = OPENID_PAY_NULL_ERROR_CODE;
					       	errorMsg = OPENID_PAY_NULL_ERROR_MSG;
		   				}
		   			}else{
		   				errorCode = ORDER_NULL_ERROR_CODE;
				       	errorMsg = ORDER_NULL_ERROR_MSG;
		   			}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("JdInterface", "test", e.toString(),"京东test",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	 
	   /**
	    *公众号回调
	    * @return
	    */
	   @RequestMapping(value="/success")
	   @ResponseBody
	   public Map<String,Object> success( HttpServletRequest request,HttpServletResponse response, String orderNum, String tradeNo ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		this.ordersDetailService.aliPaySuccess(orderNum, tradeNo, PayType.gzh, new Date());
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("JdInterface", "isHaveOpenid", e.toString(),"京东test",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
}
